lobsterlayui.main(['index', 'layer', 'form', 'element', 'table', 'tree'], {
    data: {
        $layui: null,
        selectNode: { classid: 0 },//选择树节点
        formtable: null,
        formtableoptions: {},
        treeoptions: {},
        layerindex: 0,//弹出层索引
        appid: 0,
        access_token: "",
        loginright: {}
    },
    pageload: function (right) {
        console.log(right);
        this.data.loginright = right;
        this.data.appid = lobsterlayui.GetAppId();
        this.data.access_token = lobsterlayui.GetSSOToken();
        this.initevent();
        this.treeLoad();
        this.tableLoad();
    },
    //打开弹层
    openlayer: function (title, elem, successfunction, yesfunction) {
        var self = this;

        layer.open({
            type: 1
            , title: title
            , content: $(elem).html()
            , maxmin: true
            , area: ['680px', '480px']  //宽，高
            , btn: ['保存', '取消']
            , success: function (layero, index) {
                if (successfunction) {
                    successfunction();
                }
            }
            , btn2: function (index, layero) {
                $("#LAY-app-form-reset").trigger('click');
            }
            , cancel: function () {
                $("#LAY-app-form-reset").trigger('click');
            }
            , yes: function (index, layero) {
                var submit = $('#LAY-app-front-submit');
                //监听提交
                layui.form.on('submit(LAY-app-front-submit)', function (data) {
                    var field = data.field; //获取提交的字段
                    var load = layer.msg('正在处理，请稍候', { icon: 16, time: 0, shade: [0.3, '#393D49'] });
                    console.log(field);
                    self.data.layerindex = index;
                    if (yesfunction) {
                        yesfunction(field);
                    }
                    // self.savebook(field);
                });
                submit.trigger('click');
            }
        });
    },
    //关闭弹层
    closelayer: function () {
        layer.close(this.data.layerindex);
    },
    //初始化事件
    initevent: function () {
        var self = this;

        self.data.treeoptions = {
            elem: '#Left',
            isJump: true,
            onlyIconControl: true,
            autoRefresh: true,
            customOperate: true,
            //data: treelist,
            edit: [], //操作节点的图标
            operate: function (obj) {
                // var type = obj.type; //得到操作类型：
                // var data = obj.data; //得到当前节点的数据
                // var elem = obj.elem; //得到当前节点元素
                // var id = data.id;
                // var name = data.title;
            },
            click: function (obj) {
                var data = obj.data;

                $("#Left .nodeover").removeClass("nodeover");
                $(obj.elem).find(".layui-tree-main").eq(0).addClass("nodeover");
                self.data.selectNode.classid = data.id;

                if (this.clickfun) {
                    this.clickfun();
                }
            },
            clickfun: null
        }

        self.data.formtableoptions = {
            elem: '#formTable',
            headers: lobsterlayui.GetHeaderData(),
            height: 'full-130',
            cellMinWidth: 80,
            size: 'sm',
            toolbar: '#toolbar',
            page: true,
            even: true,
            cols: [[
                { width: "70", field: 'Id', title: 'ID' },
                { width: "250", field: 'Title', title: '名称' },
                { width: "200", field: 'CreateUser', title: '创建人' },
                { width: "200", field: 'CreateTime', title: '创建时间' },
                { width: "90", field: 'ReleaseStatus', title: '发布状态', align: 'center', templet: '#statusTpl' },
                { width: "90", field: 'DelFlag', title: '状态标识', align: 'center', templet: '#flagTpl' },
                { width: "550", title: '操作', fixed: 'right', align: 'center', toolbar: '#option' }   //操作script的id                  
            ]],
            parseData: function (res) {
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.data.count,
                    data: res.data.list
                }
            }
        }

        //查找reload,通过条件，查询网格的table重载数据显示到界面
        layui.form.on("submit(LAY-app-front-search)", function (data) {
            self.searchform(data);
        });

        //添加按钮的点击事件
        layui.table.on('toolbar(formTable)', function (obj) {
            switch (obj.event) {
                case 'add':
                    self.addform();
                    break;
                case 'import':
                    window.templatecontroller.importform(self.data.selectNode.classid);
                    break;
                case 'design':
                    //window.open('/index.html');
                    break;
            };
        });

        //监听行工具事件
        layui.table.on('tool(formTable)', function (obj) {  //tool是工具条事件名，table原始容器的属性
            var data = obj.data;//当前行数据
            var layEvent = obj.event;//获得lay-event的值
            if (obj.event === "edit") {
                self.editform(data);
            }
            if (obj.event === "design") {
                self.designform(data.Id, data.ViewId);
            }
            if (obj.event === "lookdata") {
                self.lookdata(data.Id);
            }
            if (obj.event === "preview") {
                self.previewform(data.Id);
            }
            if (obj.event === "release") {
                var confirm_msg = "确认发布么?";
                layer.confirm(confirm_msg, { icon: 3, title: "提示" },
                    function (index) {
                        var Id = data.Id;
                        self.data.layerindex = index;
                        self.releaseform(Id);
                    });
            }
            // 启用停用机构
            if (obj.event === "disable" || obj.event === "enable") {

                var confirm_msg = "";
                var status = 0;
                if (data.DelFlag == 0) {
                    confirm_msg = "确认停用么?";
                    status = 1;
                }
                else {
                    confirm_msg = "确认启用么?";
                    status = 0;
                }

                layer.confirm(confirm_msg, { icon: 3, title: "提示" },
                    function (index) {
                        var Id = data.Id;
                        self.data.layerindex = index;
                        self.deleteform(Id,status);
                    });
            }
            //存为模板
            if (obj.event === "saveas") {
                window.templatecontroller.saveastemplateform(data.Id);
            }
        });

    },
    //加载树数据
    treeLoad: function () {
        var self = this;
        lobsterlayui.GETAPI('tsForm.getclasslist').then(retdata => {
            var BaseData = [];  //字典数据 
            if (retdata.list.length > 0) {
                $.each(retdata.list, function (i, base) {
                    var predata = {
                        "id": base.Id,
                        "title": base.ClassName + "(id:" + base.Id + ")",
                    };

                    BaseData.push(predata);
                });
            }
            //父节点数据
            var treedata = [{
                title: '全部'
                , id: 0
                , children: BaseData
                , spread: true
                //, disabled: true
            }];

            self.data.treeoptions.data = treedata;
            self.data.treeoptions.clickfun = function () {
                //加载表格数据
                self.tableLoad();
            }

            layui.tree.render(self.data.treeoptions);
        })
    },
    //加载表格
    tableLoad: function () {
        var self = this;
        self.data.formtableoptions.url = lobsterlayui.GetLowCodeUrl("tsForm.getformlist");
        self.data.formtableoptions.where = {
            classid: self.data.selectNode.classid,
            delflag: 0,
            keywords: $("#txtName").val()  //获取文本值
        };
        //表格绑定
        self.data.formtable = layui.table.render(self.data.formtableoptions);
        window.templatecontroller.data.formtable = self.data.formtable;
    },
    //查询
    searchform: function (formdata) {
        var self = this;
        if (self.data.formtable) {
            self.data.formtable.reload({
                where: {
                    classid: self.data.selectNode.classid,
                    delflag: 0,
                    keywords: formdata.field.txtName  //获取文本值
                },
                page: {
                    curr: 1
                }
            });
        } else {
            //加载表格数据
            self.tableLoad();
        }
    },
    //添加
    addform: function () {
        var self = this;
        self.openlayer("新增表单", "#dialog", null, function (field) {
            self.saveform(field);
        });
    },
    //编辑
    editform: function (row) {
        var self = this;
        self.openlayer("编辑表单", "#dialog", function () {
            lobsterlayui.GETAPI('tsForm.getformobject', { formid: row.Id }).then(retdata => {
                layui.form.val('formData', retdata.formobj);
            })
        }, function (field) {
            self.saveform(field);
        });
    },
    //保存
    saveform: function (field) {
        var self = this;
        lobsterlayui.POSTAPI('tsForm.saveform', field).then(retdata => {
            layer.msg("保存成功");

            self.data.formtable.reload(); //数据刷新
            self.closelayer(); //关闭弹层
        })
    },
    //删除
    deleteform: function (Id,flag) {
        var self = this;
        lobsterlayui.POSTAPI('tsForm.deleteform', { Id: Id,flag:flag }).then(retdata => {
            self.data.formtable.reload();// 数据刷新
            self.closelayer(); //关闭弹层
        })
    },
    //发布
    releaseform: function (Id) {
        var self = this;
        lobsterlayui.POSTAPI('tsForm.releaseform', { Id: Id }).then(retdata => {
            self.data.formtable.reload();// 数据刷新
            self.closelayer(); //关闭弹层
        })
    },
    //设计
    designform: function (Id, viewid) {
        window.open('/index.html#/edit/pc|form|' + Id, '', '');
    },
    //预览
    previewform: function (formid) {
        var self = this;
        var url = '/weuiapp/'+lobsterlayui.GetAppId()+'/formwirte.html?appid=' + lobsterlayui.GetAppId() + '&formid=' + formid;
        layer.open({
            type: 2
            , title: '预览问卷'
            , content: url
            //, maxmin: true
            , area: ['480px', '680px']  //宽，高
            //, btn: ['保存', '取消']
        });
    },
    //查看数据
    lookdata: function (Id) {
        var self = this;
        var url = 'formdata.html?appid=' + lobsterlayui.GetAppId() + '&formid=' + Id;
        layer.open({
            type: 2
            , title: '预览问卷'
            , content: url
            , maxmin: true
            , area: ['100%', '100%']  //宽，高
            //, btn: ['保存', '取消']
        });
    }
})

window.templatecontroller = {
    data: {
        classid: 0,
        layerindex: 0,//弹出层索引
        searchchar: '',
        formtable: null,
        templateformtable: null,
        templateformtableoptions: {
            elem: '#templateformTable',
            //headers: lobsterlayui.GetHeaderData(),
            //height: 'full',
            cellMinWidth: 80,
            size: 'sm',
            //toolbar: '#toolbar',
            //url: '/lowcode/APP20210329185258876/BookManage/?fun=getbooks&view=layui',
            page: true,
            even: true,
            cols: [[
                { width: "70", field: 'Id', hide: true },
                { width: "250", field: 'Title', title: '表单名称' },
                { width: "450", field: 'Description', title: '说明' },
                { width: "200", field: 'CreateUser', title: '创建人' },
                { width: "200", field: 'CreateTime', title: '创建时间' },
                { width: "180", title: '操作', fixed: 'right', align: 'center', toolbar: '#option2' }   //操作script的id                  
            ]],
            parseData: function (res) {
                return {
                    code: res.code,
                    msg: res.msg,
                    count: res.data.count,
                    data: res.data.data
                }
            }
        }
    },
    //导入模板
    importform: function (classid) {
        var self = this;
        self.data.classid = classid;

        layer.open({
            type: 1
            , title: "从模板导入表单"
            , content: $("#dialogtemplate").html()
            , maxmin: true
            , area: ['680px', '540px']  //宽，高
            , success: function (layero, index) {
                self.data.layerindex = index;
                self.templateformtableLoad();
            }

        });

        //监听行工具事件
        layui.table.on('tool(templateformTable)', function (obj) {  //tool是工具条事件名，table原始容器的属性
            var data = obj.data;//当前行数据
            var layEvent = obj.event;//获得lay-event的值
            if (obj.event === "import") {
                self.importformsucced(self.data.classid, data);
            }
        });

        layui.form.on("submit(btnSearchTemplate)", function (data) {
            self.data.searchchar = data.field.txttemplateformName;
            self.templateformtableReLoad();
        });
    },
    //分页加载模板表格
    templateformtableLoad: function () {
        var self = this;
        self.data.templateformtableoptions.headers = lobsterlayui.GetHeaderData();
        self.data.templateformtableoptions.url = lobsterlayui.GetLowCodeUrl("tsTemplate.searchtemplateform");
        self.data.templateformtableoptions.where = {
            searchchar: self.data.searchchar  //获取文本值
        };
        //表格绑定
        self.data.templateformtable = layui.table.render(self.data.templateformtableoptions);
    },
    templateformtableReLoad: function () {
        var self = this;
        self.data.templateformtable.reload({
            where: {
                searchchar: self.data.searchchar  //获取文本值
            },
            page: {
                curr: 1
            }
        });
    },
    //完成导入
    importformsucced: function (classid, data) {
        var self = this;
        var confirm_msg = "确认导入么?";
        layer.confirm(confirm_msg, { icon: 3, title: "提示" },
            function (index) {
                lobsterlayui.GETAPI('tsForm.importformsucceed', { classid: classid, id: data.Id }).then(retdata => {
                    layer.close(index);
                    self.data.formtable.reload();
                })
            });
    },
    //存为模板弹窗
    saveastemplateform: function (formid) {
        var self = this;
        layer.open({
            type: 1
            , title: "存为模板表单"
            , content: $("#dialogsaveastemplate").html()
            , btn: ['保存', '取消']
            , maxmin: true
            , area: ['680px', '340px']  //宽，高
            , success: function (layero, index) {
                self.data.layerindex = index;
                //绑定下拉控件数据
                self.labeltypeselectload();
                //监听提交
                layui.form.on('submit(submitsaveas)', function (data) {
                    var field = data.field; //获取提交的字段
                    var load = layer.msg('正在处理，请稍候', { icon: 16, time: 0, shade: [0.3, '#393D49'] });
                    //console.log(field);

                    self.saveastemplateformsucceed(formid, field);
                });
            }
            , yes: function (index, layero) {
                self.data.layerindex = index;
                $('#submitsaveas').trigger('click');
            }

        });
    },
    //绑定下拉控件数据
    labeltypeselectload: function () {
        var self = this;
        lobsterlayui.GETAPI('tsTemplate.getlabeltype').then(retdata => {
            var data = retdata['data'];

            $("#labeltype1").html("");
            $("#labeltype2").html("");
            $("#labeltype3").html("");
            data.forEach(element => {
                if (element.Type == "1") {
                    $("#labeltype1").append("<option value=\"" + element.Code + "\" label=\"" + element.Name + "\">" + element.Name + "</option>");
                }
                else if (element.Type == "2") {
                    $("#labeltype2").append("<option value=\"" + element.Code + "\" label=\"" + element.Name + "\">" + element.Name + "</option>");
                }
                else if (element.Type == "3") {
                    $("#labeltype3").append("<option value=\"" + element.Code + "\" label=\"" + element.Name + "\">" + element.Name + "</option>");
                }
            });
            //重新渲染
            layui.form.render();
        })
    },
    //存为模板完成
    saveastemplateformsucceed: function (formid, field) {
        var self = this;

        console.log(formid);
        console.log(field);
        var param = {
            formid: formid,
            labeltype1: field.labeltype1,
            labeltype2: field.labeltype2,
            labeltype3: field.labeltype3
        }
        lobsterlayui.GETAPI('tsForm.saveastemplateform', param).then(retdata => {
            layer.closeAll();
        })
    }
}